<template>
  <div>
    <avue-crud
    v-if="option.column"
    :data="data.data"
    :option="option"
    @row-save="create"
    @row-update="update"
    @row-del="remove"
    :page.sync="page"
    @on-load="pageChange"
    @search-change="search"
    @search-reset="searchReset"
    ></avue-crud>
  </div>
</template>

<script lang="ts">
import { Vue, Component, Prop } from 'vue-property-decorator'

@Component({})
export default class ResourceCrud extends Vue {
  @Prop(String) resource!: string
  data: any = {}

  option: any = {}

  page: any = {
    total: 0,
    pageSize: 2,
    pageSizes: [2, 5, 10, 50]
  }

  query: any = {
    limit: 2,
    page: 1
  }

  async fetchOption () {
    const res = await this.$http.get(`${this.resource}/option`)
    this.option = res.data
  }

  async fetch () {
    const res = await this.$http.get(`${this.resource}`, {
      params: {
        query: this.query
      }
    })
    this.data = res.data
    this.page.total = res.data.total
  }

  async search (where, done) {
    for (const k in where) {
      const field = this.option.column.find(v => v.prop === k)
      if (field.regex) {
        where[k] = { $regex: where[k] }
      }
    }
    this.query.where = where
    this.fetch()
    done()
  }

  async searchReset () {
    delete this.query.where
    this.fetch()
  }

  async create (row, done) {
    await this.$http.post(`${this.resource}`, row)
    this.$message.success('创建成功')
    this.fetch()
    done()
  }

  async update (row, index, done) {
    const data = JSON.parse(JSON.stringify(row))
    for (const i in data) {
      const e = /^\$/
      if (e.test(i)) {
        delete data[i]
      }
    }
    await this.$http.put(`${this.resource}/${row._id}`, data)
    this.$message.success('更新成功')
    this.fetch()
    done()
  }

  async remove (row) {
    const str = await this.$confirm('是否确认删除？', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }).catch(err => err)
    
    if(str !== 'confirm'){
      return this.$message.info('已经取消删除')
    }else{
      this.$http.delete(`${this.resource}/${row._id}`)
      this.$message.success('删除成功')
      this.fetch()
    }
  }

  pageChange ({ pageSize, currentPage }) {
    this.query.limit = pageSize
    this.query.page = currentPage
    this.fetch()
  }

  created () {
    this.fetchOption()
    this.fetch()
  }
}
</script>

<style>

</style>
